<template>
  <div>
    <el-form ref="formRef" :model="postForm" :rules="postRules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="postForm.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章封面首图" prop="firstPicture">
            <el-input v-model="postForm.firstPicture" placeholder="文章封面首图，用于文章展示" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="文章描述" prop="description">
        <mavon-editor v-model="postForm.description" />
      </el-form-item>

      <el-form-item label="文章正文" prop="content">
        <mavon-editor v-model="postForm.content" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分类" prop="cate">
            <el-select
              v-model="postForm.cate"
              :allow-create="true"
              :filterable="true"
              placeholder="请选择分类,或输入添加新分类"
              style="width: 100%"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签" prop="tagList">
            <el-select
              v-model="postForm.tagList"
              :allow-create="true"
              :filterable="true"
              :multiple="true"
              placeholder="请选择标签,或输入添加新标签"
              style="width: 100%"
            >
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="字数" prop="words">
            <el-input
              v-model="postForm.words"
              placeholder="请输入文章字数（自动计算阅读时长）"
              type="number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="阅读时长(分钟)" prop="readTime">
            <el-input
              v-model="postForm.readTime"
              placeholder="请输入阅读时长（可选）默认为(字数 / 200)"
              type="number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="浏览次数" prop="views">
            <el-input
              v-model="postForm.views"
              placeholder="请输入被浏览次数（可选）默认为 0"
              type="number"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item style="text-align: right">
        <el-button type="primary" @click="dialogVisible = true">保存</el-button>
      </el-form-item>
    </el-form>
    <!--    保存之后对文章进行可见性设置-->
    <security-setting-dialog
      :form="postForm"
      :is-show="dialogVisible"
      :loading="loading"
      :radio="radio"
      @cancel="dialogVisible = false"
      @save="onSubmit"
    />
  </div>
</template>

<script>
  import { getBlogById, getCategoryAndTag, saveBlog, updateBlog } from '@/api/blog'
  import SecuritySettingDialog from '@/views/blog/post/components/SecuritySettingDialog'

  export default {
    name: 'PostWriter',
    components: { SecuritySettingDialog },
    data() {
      return {
        categoryList: [],
        tagList: [],
        dialogVisible: false,
        radio: 1,
        postForm: {
          title: '',
          firstPicture: '',
          description: '',
          content: '',
          cate: null,
          tagList: [],
          words: null,
          readTime: null,
          views: 0,
          appreciation: false,
          recommend: false,
          commentEnabled: false,
          top: false,
          published: false,
          password: '',
        },
        postRules: {
          title: [{ required: true, message: '请输入标题', trigger: 'change' }],
          firstPicture: [{ required: true, message: '请输入首图链接', trigger: 'change' }],
          cate: [{ required: true, message: '请选择分类', trigger: 'change' }],
          tagList: [{ required: true, message: '请选择标签', trigger: 'change' }],
          words: [{ required: true, message: '请输入文章字数', trigger: 'change' }],
        },
        loading: false,
      }
    },
    computed: {},
    watch: {
      'postForm.words'(newValue) {
        this.postForm.readTime = newValue ? Math.round(newValue / 200) : null
      },
    },
    created() {
      this.getData()
      if (this.$route.params.id) {
        this.getBlog(this.$route.params.id)
      }
    },
    methods: {
      getData() {
        getCategoryAndTag()
          .then((res) => {
            this.categoryList = res.data.categories
            this.tagList = res.data.tags
          })
          .catch((err) => {
            console.log(err)
          })
      },
      getBlog(id) {
        getBlogById(id).then((res) => {
          const data = res.data
          this.computeCategoryAndTag(data)
          this.postForm = data
          this.radio = this.postForm.published ? (this.postForm.password !== '' ? 3 : 1) : 2
        })
      },
      computeCategoryAndTag(post) {
        post.cate = post.category.id
        post.tagList = []
        post.tags.forEach((tag) => {
          post.tagList.push(tag.id)
        })
      },
      onSubmit() {
        if (
          this.radio === 3 &&
          (this.postForm.password === '' || this.postForm.password === null)
        ) {
          return this.msgError('密码保护模式必须填写密码')
        }
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.loading = true
            // 如果是仅自己可见
            if (this.radio === 2) {
              this.postForm.appreciation = false
              this.postForm.recommend = false
              this.postForm.commentEnabled = false
              this.postForm.top = false
              this.postForm.published = false
            } else {
              this.postForm.published = true
            }
            if (this.radio !== 3) {
              this.postForm.password = ''
            }
            if (this.$route.params.id) {
              this.postForm.category = null
              this.postForm.tags = null
              updateBlog(this.postForm).then((res) => {
                this.msgSuccess(res.msg)
                this.$router.push('/blog/post/list')
              })
            } else {
              saveBlog(this.postForm).then((res) => {
                this.msgSuccess(res.msg)
                this.$router.push('/blog/post/list')
              })
            }
            setTimeout(() => {
              this.loading = false
            }, 500)
          } else {
            this.dialogVisible = false
            return this.msgError('请填写必要的选项')
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
